package zjua4r.googlemap.demo;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;

public class GoogleMapsActivity extends MapActivity {
    
	MapView mapView;
	MarkerOverlay markerOverlay;
	MapController controller;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        mapView = (MapView) findViewById(R.id.mapView);
        mapView.setBuiltInZoomControls(true);
        mapView.displayZoomControls(true);
        mapView.setStreetView(true);
        
        controller = mapView.getController();
        GeoPoint p = new GeoPoint(0,0);
        controller.animateTo(p);
        controller.setZoom(15);
        
        Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.blue);
        markerOverlay = new MarkerOverlay(bmp);
        markerOverlay.setCurrentGeoPoint(p);
        mapView.getOverlays().add(markerOverlay);
        
        openGPSSettings();
        startGPS();
    }

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
	
	private LocationManager locationManager;
	
    private void openGPSSettings() {
        LocationManager alm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        if (alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
            Toast.makeText(this, "GPS模块正常", Toast.LENGTH_SHORT).show();
            return;
        }

        Toast.makeText(this, "请开启GPS！", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
        startActivityForResult(intent,0); //此为设置完成后返回到获取界面
    }
    
    private void startGPS()
    {
    	this.locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    	registerLocationListener();
    }
    
	private LocationListener gpsListener=null;
	private LocationListener networkListner=null;
	private boolean gpsHasSignal = false;
	private void registerLocationListener(){
		networkListner=new MyLocationListner();
		locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 3000, 0, networkListner);
		gpsListener=new MyLocationListner();
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 0, gpsListener);
	}

    Location currentLocation;
    class MyLocationListner implements LocationListener{
    	@Override
    	public void onLocationChanged(Location location) {    		
    		if(LocationManager.GPS_PROVIDER.equals(location.getProvider()))
    			gpsHasSignal = true;
    		
    		// Called when a new location is found by the location provider.
    		Log.v("GPSTEST", "Got New Location of provider:"+location.getProvider());
    		if(currentLocation!=null){
    			if(isBetterLocation(location, currentLocation)){
    				Log.v("GPSTEST", "It's a better location");
    				currentLocation=location;
    				showLocation(location);
    			}
    			else{
    				Log.v("GPSTEST", "Not very good!");
    			}
    		}
    		else{
    			Log.v("GPSTEST", "It's first location");
    			currentLocation=location;
    			showLocation(location);
    		}
    		//移除基于LocationManager.NETWORK_PROVIDER的监听器
    		if(gpsHasSignal && LocationManager.NETWORK_PROVIDER.equals(location.getProvider())){
    			locationManager.removeUpdates(this);
    		}
    	}
     
    	//后3个方法此处不做处理
    	public void onStatusChanged(String provider, int status, Bundle extras) {
    	}
     
    	public void onProviderEnabled(String provider) {
    	}
     
    	public void onProviderDisabled(String provider) {
    	}
    };
    
    private void showLocation(Location location){
    	//纬度
    	Log.v("GPSTEST","Latitude:"+location.getLatitude());
    	//经度
    	Log.v("GPSTEST","Longitude:"+location.getLongitude());
    	//精确度
    	Log.v("GPSTEST","Accuracy:"+location.getAccuracy());
    	//Location还有其它属性，请自行探索
    	GeoPoint p = new GeoPoint((int)(location.getLatitude()*1E6),(int)(location.getLongitude()*1E6));    	
    	PointLatLng fixedLoaction = OffsetDecoder.Instance.ConvertToFixedLocation(location.getLatitude(), location.getLongitude());
    	
    	if(fixedLoaction != null)
    		p = new GeoPoint(fixedLoaction.getLatitudeE6(), fixedLoaction.getLongitudeE6());
    	
    	this.markerOverlay.setCurrentGeoPoint(p);
    	this.controller.animateTo(p);
    }
    private static final int CHECK_INTERVAL = 1000 * 60;
	protected boolean isBetterLocation(Location location,
			Location currentBestLocation) {
		if (currentBestLocation == null) {
			// A new location is always better than no location
			return true;
		}
 
		// Check whether the new location fix is newer or older
		long timeDelta = location.getTime() - currentBestLocation.getTime();
		boolean isSignificantlyNewer = timeDelta > CHECK_INTERVAL;
		boolean isSignificantlyOlder = timeDelta < -CHECK_INTERVAL;
		boolean isNewer = timeDelta > 0;
 
		// If it's been more than two minutes since the current location,
		// use the new location
		// because the user has likely moved
		if (isSignificantlyNewer) {
			return true;
			// If the new location is more than two minutes older, it must
			// be worse
		} else if (isSignificantlyOlder) {
			return false;
		}
 
		// Check whether the new location fix is more or less accurate
		int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation
				.getAccuracy());
		boolean isLessAccurate = accuracyDelta > 0;
		boolean isMoreAccurate = accuracyDelta < 0;
		boolean isSignificantlyLessAccurate = accuracyDelta > 200;
 
		// Check if the old and new location are from the same provider
		boolean isFromSameProvider = isSameProvider(location.getProvider(),
				currentBestLocation.getProvider());
 
		// Determine location quality using a combination of timeliness and
		// accuracy
		if (isMoreAccurate) {
			return true;
		} else if (isNewer && !isLessAccurate) {
			return true;
		} else if (isNewer && !isSignificantlyLessAccurate
				&& isFromSameProvider) {
			return true;
		}
		return false;
	}
 
	/** Checks whether two providers are the same */
	private boolean isSameProvider(String provider1, String provider2) {
		if (provider1 == null) {
			return provider2 == null;
		}
		return provider1.equals(provider2);
	}
}